//配置路由器
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
import routes from "./routes";
import store from "@/store";


//先把VueRouter原型对象上的push、replace保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push|replace
//第一个参数：告诉原来的push方法，往哪里跳转（传递哪些参数）
//第二个参数：成功回调
//第三个参数：失败回调

VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

//配置路由
const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
});
//全局前置路由守卫
router.beforeEach(async (to, from, next) => {
    //获取token、用户名name
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    //判断是否登录
    if (token) {
        //已登录，去登录、注册页
        if (to.path == "/login" || to.path == "/register") {
            next("/home");
        } else {
            //去其他页面，判断是否有用户信息
            if (name) {
                //有用户信息
                next();
            } else {
                //无用户信息
                try {
                    //发请求获取用户信息
                    await store.dispatch("user/userInfo");
                    next();
                } catch (error) {
                    //token过期,退出登录来清除信息
                    await store.dispatch("user/userLogout");
                    //重新登录
                    next("/login");
                }
            }
        }
    } else {
        //未登录
        let toPath = to.path;
        if (toPath == "/shopcart" || toPath == "/center/myorder" || toPath == "/center/grouporder") {
            //去登录状态下才能去的页面，携带路径跳转至登录页
            next(`/login?redirect=${toPath}`);
        } else {
            //去其他页面
            next();
        }
    }
})

export default router;